package com.fh.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.fh.address.entity.MemberReceiveAddress;
import com.fh.entity.Cart;
import com.fh.member.entity.Member;
import com.fh.member.service.MemberService;
import com.fh.order.entity.Order;
import com.fh.order.entity.OrderItem;
import com.fh.order.entity.OrderOperateHistory;
import com.fh.order.mapper.OrderMapper;
import com.fh.order.service.OrderItemService;
import com.fh.order.service.OrderOperateHistoryService;
import com.fh.order.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fh.rabbit.DeadSendMessageController;
import com.fh.service.CartService;
import com.fh.sku.entity.SkuStock;
import com.fh.sku.service.SkuStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import utils.RedisKey;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author zs
 * @since 2021-10-21
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private CartService cartService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private OrderOperateHistoryService orderOperateHistoryService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SkuStockService skuStockService;
    @Autowired
    private DeadSendMessageController deadSendMessageController;
    @Override
    @Transactional
    public String createOrder(MemberReceiveAddress memberReceiveAddress, Integer payType, String phone, BigDecimal totalMoney) {
        List<Cart> cartList = cartService.getCar(phone);
        String orderSn = IdWorker.getIdStr();
        Order order=getOrder(orderSn,payType,memberReceiveAddress,phone,totalMoney);
        super.save(order);
        //订单的商品信息
        List<OrderItem> orderItem= getOrderItem(cartList,order.getId(),orderSn);
        orderItemService.saveBatch(orderItem);
      //订单操作记录
        OrderOperateHistory orderOperateHistory=getOrderOperateHistory(order.getId(),memberReceiveAddress.getMemberId());
        orderOperateHistoryService.save(orderOperateHistory);
        //删除redis中的数据
        String cartKey = RedisKey.getCartKey(phone);
        cartList.forEach(product->{
            redisTemplate.opsForHash().delete(cartKey,product.getSkuCode());
            updateStock(product.getSkuCode(),product.getCount());

        });
        //将订单号发送到消息队列中
        deadSendMessageController.sendMessage(orderSn);
        return orderSn;


    }

    private void updateStock(String skuCode, Integer count) {
        QueryWrapper<SkuStock> wrapper=new QueryWrapper<>();
        wrapper.eq("sku_code",skuCode);
        SkuStock skuStock = skuStockService.getOne(wrapper);
        skuStock.setStock(skuStock.getStock()-count);
        skuStockService.updateById(skuStock);
    }

    private OrderOperateHistory getOrderOperateHistory(Long orderId, Long memberId ) {
        OrderOperateHistory orderOperateHistory=new OrderOperateHistory();
        orderOperateHistory.setOrderId(orderId);
        orderOperateHistory.setCreateTime(new Date());
        orderOperateHistory.setOrderStatus(0);
        Member member = memberService.getById(memberId);
        orderOperateHistory.setOperateMan(member.getNickname());
        return orderOperateHistory;


    }

    //组装商品信息
    private  List<OrderItem> getOrderItem(List<Cart> cartList, Long id, String orderSn) {
        List<OrderItem> orderItems=new ArrayList<>();
        cartList.forEach(prodcut->{
            OrderItem orderItem=new OrderItem();
            orderItem.setOrderId(id);
            orderItem.setOrderSn(orderSn);
            orderItem.setProductId(prodcut.getProductId());
            orderItem.setProductPic(prodcut.getPic());
            orderItem.setProductName(prodcut.getProductName());
            orderItem.setProductPrice(prodcut.getPrice());
            orderItem.setProductQuantity(prodcut.getCount());
            orderItem.setProductSkuCode(prodcut.getSkuCode());
            orderItem.setProductAttr(prodcut.getSpData());
            orderItems.add(orderItem);
        });
        return  orderItems;
    }

    private Order getOrder( String orderSn, Integer payType, MemberReceiveAddress address, String phone, BigDecimal totalMoney) {
        Order order=new Order();
        order.setMemberId(address.getMemberId());
        order.setOrderSn(orderSn);
        order.setCreateTime(new Date());
        order.setMemberUsername(phone);
        order.setTotalAmount(totalMoney);
        order.setPayAmount(totalMoney);
        order.setPayType(payType);
        order.setSourceType(0);
        order.setStatus(0);
        order.setOrderType(0);
        order.setAutoConfirmDay(7);
        order.setReceiverName(address.getName());
        order.setReceiverPhone(address.getPhoneNumber());
        order.setReceiverProvince(address.getProvince());
        order.setReceiverCity(address.getCity());
        order.setReceiverRegion(address.getRegion());
        order.setReceiverDetailAddress(address.getDetailAddress());
        order.setDeleteStatus(0);
        order.setConfirmStatus(0);
        return  order;

    }
}
